package com.andyliu.util;

import com.andyliu.common.Project;
import com.andyliu.controller.BaseController;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @packageName: com.andyliu.util
 * @user: andyliu
 * @date: 2021/7/31 15:40
 * @email 115176513@qq.com
 * @description: MybatisPlus工具类
 */
@Component
public class MybatisGenUtil {

    @Autowired
    private Project project;

    @Autowired
    private DataSourceProperties dataSource;

    GlobalConfig config = new GlobalConfig();

    public void init(){
        config.setBaseResultMap(true);
        config.setBaseColumnList(true);
        config.setAuthor(project.getAuthor());
        config.setOpen(false);
        config.setSwagger2(true);
        config.setOutputDir(System.getProperty("user.dir") + "/src/main/java");
    }

    public void generator(String packageName,String tableName,String modulName,String prefix){
        if(packageName==null || "".equals(packageName)){
            packageName = "com.andyliu.test";
        }
        this.init();
        AutoGenerator generator = new AutoGenerator();
        generator.setGlobalConfig(config);
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDriverName(dataSource.getDriverClassName());
        dataSourceConfig.setUrl(dataSource.getUrl());
        dataSourceConfig.setUsername(dataSource.getUsername());
        dataSourceConfig.setPassword(dataSource.getPassword());
        generator.setDataSource(dataSourceConfig);
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setModuleName(modulName);
        packageConfig.setParent(packageName);
        generator.setPackageInfo(packageConfig);
        /**
         * 自定义配置
         */
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        String templatePath = "/templates/controller.java.vm";
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return System.getProperty("user.dir") + "/src/main/java/"+packageConfig.getParent().replace(".","/")+ modulName+"/"+tableInfo.getEntityName();
            }
        });
        focList.add(new FileOutConfig("/templates/mapper.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return System.getProperty("user.dir") + "/src/main/java/"+packageConfig.getParent().replace(".","/")+ modulName+"/"+tableInfo.getMapperName();
            }
        });
        focList.add(new FileOutConfig("/templates/service.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return System.getProperty("user.dir") + "/src/main/java/"+packageConfig.getParent().replace(".","/")+ modulName+"/"+tableInfo.getXmlName();
            }
        });
        focList.add(new FileOutConfig("/templates/serviceImpl.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return System.getProperty("user.dir") + "/src/main/java/"+packageConfig.getParent().replace(".","/")+ modulName+"/"+tableInfo.getServiceImplName();
            }
        });
        //这块是set到上面自定义配置中
//        cfg.setFileOutConfigList(focList);
        //set进去代码生成器对象中
        generator.setCfg(cfg);
        generator.setTemplate(TemplateGenerate());
        /**
         * 策略配置
         */
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setInclude(tableName);
        //实体是否为lombok模型（默认 false）
        strategy.setEntityLombokModel(true);
        //生成 @RestController 控制器
        strategy.setRestControllerStyle(false);
        strategy.setSuperControllerClass(BaseController.class);
        //驼峰转连字符
        strategy.setControllerMappingHyphenStyle(true);
        //表名前缀
        strategy.setTablePrefix(prefix);
        generator.setStrategy(strategy);
        generator.setTemplateEngine(new VelocityTemplateEngine());
//      generatorHtml("packag","table");
        generator.execute();

    }

    public void generatorHtml(String packageName,String tableName,String modul,String prefix){
        if(packageName==null || "".equals(packageName)){
            packageName = "com.andyliu.test";
        }
        this.init();
        GeneratorHtml generator = new GeneratorHtml();
        generator.setGlobalConfig(config);
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDriverName(dataSource.getDriverClassName());
        dataSourceConfig.setUrl(dataSource.getUrl());
        dataSourceConfig.setUsername(dataSource.getUsername());
        dataSourceConfig.setPassword(dataSource.getPassword());
        generator.setDataSource(dataSourceConfig);
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setModuleName(modul);
        packageConfig.setParent(packageName);
        generator.setPackageInfo(packageConfig);
        /**
         * 自定义配置
         */
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        String templatePath = "/templates/add.vm";
        List<FileOutConfig> focList = new ArrayList<>();
        //这块是set到上面自定义配置中
        cfg.setFileOutConfigList(focList);
        //set进去代码生成器对象中
        generator.setCfg(cfg);
        /**
         * 策略配置
         */
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setInclude(tableName);
        //实体是否为lombok模型（默认 false）
        strategy.setEntityLombokModel(true);
        //生成 @RestController 控制器
        strategy.setRestControllerStyle(false);

        //驼峰转连字符
        strategy.setControllerMappingHyphenStyle(true);
        //表名前缀
        strategy.setTablePrefix(prefix);
        generator.setStrategy(strategy);
        generator.setTemplateEngine(new VelocityTemplateEngine());
        generator.execute(modul);

    }
    private  TemplateConfig TemplateGenerate(){
        TemplateConfig templateConfig = new TemplateConfig()
                .setController("/templates/controller.java")
                .setXml("/templates/mapper.xml")
                .setService("/templates/service.java")
                .setServiceImpl("/templates/serviceImpl.java")
                ;
        return templateConfig;
    }
}
